package cl.mt.util.bd;
/**
 * Septiembre de 2004
 * @author Jorge Velasco
 */

import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.naming.InitialContext;
import javax.sql.DataSource;

public abstract class DatosTabla {

	protected Connection con = null;
	protected PreparedStatement pst = null;
	protected ResultSet rs = null;
	protected boolean isInicializado = false;

	/*
	 * Inicializa la Conexion a la BD.
	 */
	public void setConnection() throws Exception {
		if (isInicializado)
			return;

		try {
			Class.forName(DatosConexion.Driver);
		} catch (Exception e) {
			System.out.println("Error al Generar Driver: " + e.getMessage());
			throw e;
		}
		isInicializado = true;
	}

	public void validarDriver() throws Exception {
		try {
			Class d = Class.forName(DatosConexion.Driver);
			Driver dr = (Driver) d.newInstance();
		} catch (Exception e) {
			System.out.println("Error al Generar Driver: " + e.getMessage());
			throw e;
		}
		isInicializado = true;
	}

	/*
	 * Obtiene Connecion a la BD.
	 */
	//	public void getConnection() throws Exception {
	//		setConnection();
	//		if (con == null || con.isClosed())
	//			con = DriverManager.getConnection(DatosConexion.Url, DatosConexion.User, DatosConexion.Pwd);
	//	}

	public void getConnection() throws Exception {
		try {
			InitialContext ic = new InitialContext();
			DataSource ds = (DataSource) ic.lookup(DatosConexion.JNDI_JDBC);
			con = ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * Ejecuta una Consulta t Devuelve el Resulset. 
	 */
	protected ResultSet executeQuery(String querySQL, Parametro[] paramIn) throws SQLException {

		if (querySQL == null || "".equals(querySQL))
			return null;
		if (con == null || con.isClosed())
			return null;

		System.out.println(querySQL);
		if (pst != null)
			pst.clearParameters();
		pst = con.prepareStatement(querySQL);
		//log.info("Niveles CONCURRENCIA 2(" +  pst.getResultSetType() + "," + pst.getResultSetConcurrency() + "," + pst.getQueryTimeout() + ")");

		for (int i = 0; paramIn != null && i < paramIn.length; i++) {
			pst.setObject(1 + i, paramIn[i].getValue(), paramIn[i].getTypeSQL());
		}
		rs = pst.executeQuery();

		//log.debug("Ejecuntando Query [" + querySQL + "]");

		return rs;
	}

	/*
	 * Ejecuta una Consulta t Devuelve el Resulset. 
	 */
	protected int executeUpdate(String querySQL, Parametro[] paramIn) throws SQLException {

		if (querySQL == null || "".equals(querySQL))
			return 0;
		if (con == null || con.isClosed())
			return 0;

		System.out.println(querySQL);
		//log.debug("Ejecuntando Query [" + querySQL + "]");
		if (pst != null)
			pst.clearParameters();
		pst = con.prepareStatement(querySQL);

		for (int i = 0; paramIn != null && i < paramIn.length; i++) {
			System.out.println("Param [" + i + "]=='" + paramIn[i].getValue() + "'");
			pst.setObject(1 + i, paramIn[i].getValue(), paramIn[i].getTypeSQL());
		}

		int res = pst.executeUpdate();

		return res;
	}

	/*
	 * Cierra la Conexion a la BD.
	 */
	public void closeConnection() {
		try {
			if (rs != null)
				rs.close();
		} catch (Exception e) {
		}
		try {
			if (pst != null)
				pst.close();
		} catch (Exception e) {
		}
		try {
			if (con != null && !con.isClosed())
				con.close();
		} catch (Exception e) {
		}

		rs = null;
		pst = null;
		con = null;
	}

	protected Parametro getParametro(Object o, int typeCampo) {
		return new Parametro(o, typeCampo);

	}

	/*
	 * Elimina los Caracteres Invalidos 
	 */
	protected String limpiaString(String entrada) {
		if (entrada == null)
			return "";
		char charControlM[] = { 0x0d };
		Vector caracteresMalos = new Vector();
		caracteresMalos.add(new String(charControlM));
		caracteresMalos.add(new String("\t"));
		caracteresMalos.add(new String("\n"));
		caracteresMalos.add(new String(";"));

		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < entrada.length(); i++) {
			// si el i-esimo caracter no est� entre los malos, lo agrego
			if (!caracteresMalos.contains(entrada.substring(i, i + 1)))
				buffer.append(entrada.substring(i, i + 1));
			else
				buffer.append(" ");
		}

		return buffer.toString();
	}

	protected Integer formatInteger(Object o) {
		if (o == null)
			return null;

		try {
			return new Integer(o.toString());
		} catch (NumberFormatException e) {
		}
		return null;
	}

	protected Long formatLong(Object o) {
		if (o == null)
			return null;

		try {
			return new Long(o.toString());
		} catch (NumberFormatException e) {
		}
		return null;
	}

	protected String formatString(Object o) {
		if (o == null)
			return null;

		return o.toString();
	}

	protected Date formatDate(Date o) {
		if (o == null)
			return null;

		return new Date(o.getTime());
	}

	protected Timestamp formatTimestamp(Date o) {
		if (o == null)
			return null;

		return new Timestamp(o.getTime());
	}

	protected Date formatToFecha(String dia, String hora) {
		if (dia == null)
			return null;
		if (hora == null)
			hora = "000000";

		try {
			return sdfFecha.parse(dia + hora);
		} catch (ParseException e) {
		}

		return null;
	}

	SimpleDateFormat sdfFecha = new SimpleDateFormat("yyyyMMddHHmmss");
	SimpleDateFormat sdfDia = new SimpleDateFormat("yyyyMMdd");
	SimpleDateFormat sdfHora = new SimpleDateFormat("HHmmss");

	protected String formatDia(Date fecha) {
		if (fecha == null)
			return "";
		return sdfDia.format(fecha);
	}

	protected String formatHora(Date fecha) {
		if (fecha == null)
			return "";
		return sdfHora.format(fecha);
	}

	protected String getParametrosLista(int largo) {
		String str = "";
		for (int i = 1; i <= largo; i++) {
			str += "?,";
		}
		if (str.length() > 0)
			str = str.substring(0, str.length() - 1);
		return str;
	}

}
